<?php

//weixin.shjieta.com.cn/FrontWeb/default.aspx
error_reporting(E_ALL);
include_once ('Weimod.php');
session_start();


/*
 * http://www.shjieta.com.cn/shop/plugin/Wechat/action_weimod.php?get=valid
 * weixin server validation
 */
    
switch($_GET["get"]){
    case "valid":  $weimod = new Weimod();$result = $weimod->valid(); echo $result;break;
    case "refresh":refreshToken();break;
    case "Oauth":getOpenID();break;
}
exit;

/*
 * weixin get Oauth token openid
 */
function getOpenID() {
    $weimod = new Weimod();
    $code = isset($_GET['code']) ? $_GET['code'] : '';
    $index = isset($_GET['t']) ? ('&t=' . $_GET['t']) : ''; 
    if (!$code) {
        $url = 'http://www.shjieta.com.cn/shop/plugin/Wechat/action_weimod.php?get=Oauth' . $index; 
        $result = $weimod->GetWeimobCode($url, 'snsapi_userinfo'); 
        echo $result;exit;
        echo '<script>';
        echo "window.location.href='" . $result . "'";
        echo '</script>';
        exit;
    } else {
        $result = $weimod->getOauthAccessToken();
        $index = isset($_GET['t']) ? intval($_GET['t']) + 1 : 1;
        if (array_key_exists('error', $result)) {
            //执行3次就停止
            if ($index <= 3) {
                $url = 'http://www.shjieta.com.cn/shop/plugin/Wechat/action_weimod.php?get=Oauth&t=' . $index;
                echo '<script>';
                echo "window.location.href='" . $url . "'";
                echo '</script>';
                exit;
            } else {
                echo 'operation error';
            }
        } else {
            if (array_key_exists("access_token", $result)) {
                $_SESSION["ganso_wx"]["access_token"] = $result['access_token'];
            }
            if (array_key_exists("refresh_token", $result)) {
                $_SESSION["ganso_wx"]["refresh_token"] = $result['refresh_token'];
            }
            if (array_key_exists("openid", $result)) {
                $_SESSION["ganso_wx"]["openid"] = $result['openid'];
            }

            $result = $weimod->getUSERINFO($_SESSION["ganso_wx"]["access_token"]);
            
        }
    }

    exit;
}


/*
 * weixin refresh token
 */
function refreshToken() {
     $weimod = new Weimod();
    $refresh_token = isset($_SESSION["ganso_wx"]) && !empty($_SESSION["ganso_wx"]['refresh_token']) ? $_SESSION["ganso_wx"]['refresh_token'] : '';

    if (!empty($refresh_token)) {
        $result = $weimod->getOauthRefreshToken($refresh_token);
        if (array_key_exists("refresh_token", $result)) {
            $_SESSION["ganso_wx"]["refresh_token"] = $result['refresh_token'];
        }
        if (array_key_exists("openid", $result)) {
            $_SESSION["ganso_wx"]["openid"] = $result['openid'];
        }
    }

    exit;
}
?>